using Digitalmes.Domain.Entities.Mes.Processes;

namespace Digitalmes.Application.Mes.Processes.StepStandards.Commands;

/// <summary>
/// 工艺标准创建命令。
/// </summary>
public sealed record CreateStepStandardCommand(ProcStepStandardDto StepStandard) : IRequest<IResult<bool>>;

internal sealed class CreateStepStandardCommandHandler(IRepository<ProcStepStandard> repo) : IRequestHandler<CreateStepStandardCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateStepStandardCommand request, CancellationToken cancellationToken)
    {
        // 检查编码不能重复
        var exists = await repo.AsQueryable()
            .WhereIF(request.StepStandard.StepTaskId > 0, m => m.StepTaskId == request.StepStandard.StepTaskId)
            .AnyAsync(m => m.StepId == request.StepStandard.StepId && m.ParameterCode == request.StepStandard.ParameterCode, cancellationToken);
        if (exists)
        {
            return Result.Failure("工序参数编码已存在");
        }

        var standard = request.StepStandard.Adapt<ProcStepStandard>();
        standard.Owner = standard.StepTaskId > 0 ? "StepTask" : "Step";
        var ok = await repo.InsertAsync(standard, cancellationToken);
        return Result.From(ok);
    }
}
